package com.server;

import com.sun.mail.smtp.SMTPTransport;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * @author sad
 */
public class MailSender {

    private final String mailServer;
    private final String emailAccount;
    private final String password;

    public MailSender(String mailServer, String emailAccount, String password) {
        this.mailServer = mailServer;
        this.emailAccount = emailAccount;
        this.password = password;
    }

    private String getUserNameFromMail(String email) {
        int index = email.indexOf("@");
        return email.substring(0, index);
    }

    public void sendMesssage(String title, MimeMultipart mimeMultipart, String receiver) throws MessagingException, IOException {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", mailServer);
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");



        /*
         If set to false, the QUIT command is sent and the connection is immediately closed. If set 
         to true (the default), causes the transport to wait for the response to the QUIT command.

         ref :   http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
         http://forum.java.sun.com/thread.jspa?threadID=5205249
         smtpsend.java - demo program from javamail
         */
        props.put("mail.smtps.quitwait", "false");
        Session session = Session.getInstance(props, null);




        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(getUserNameFromMail(emailAccount) + "@gmail.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver, false));

        msg.setSubject(title);
        msg.setContent(mimeMultipart);
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport) session.getTransport("smtps");

        t.connect("smtp.gmail.com", getUserNameFromMail(emailAccount), password);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    }
}
